import hashlib
import random
import requests
import googletrans

import config


class Translator:
    def translate(self, text: str, from_lang: str = 'en', to_lang: str = 'zh', domain: str = 'it'):
        pass


class BaiduTranslator(Translator):
    """
    文档 https://fanyi-api.baidu.com/doc/22
    """
    
    def __init__(self):
        # url = 'http://api.fanyi.baidu.com/api/trans/vip/fieldtranslate'
        self.url = 'https://fanyi-api.baidu.com/api/trans/vip/fieldtranslate'
    
    def __sign(self, q: str, salt: int, domain: str) -> str:
        string_join = config.appid + q + str(salt) + domain + config.secretKey
        return hashlib.md5(string_join.encode()).hexdigest()
    
    def __get_params(self, q: str, from_lang: str = 'auto', to_lang: str = 'zh', domain: str = 'it') -> dict:
        salt = random.randint(32768, 65536)
        params = {
            'appid': config.appid,
            'q': q,
            'from': from_lang,
            'to': to_lang,
            'salt': str(salt),
            'domain': domain,
            'sign': self.__sign(q, salt, domain)
        }
        return params
    
    def translate(self, text: str, from_lang: str = 'en', to_lang: str = 'zh', domain: str = 'it') -> str:
        response = requests.get(
            url=self.url,
            params=self.__get_params(text, from_lang, to_lang, domain)
        )
        print(response.text)
        # for paragraph in response.json()['trans_result']:
        #     print(paragraph['src'])
        
        result = [paragraph['dst'] for paragraph in response.json()['trans_result']]
        # for paragraph in response.json()['trans_result']:
        #     print(paragraph['dst'])
        return '\n'.join(result)


from googletrans import Translator


class GoogleTranslator(Translator):
    
    def translate(self, text: str, from_lang: str = 'en', to_lang: str = 'zh-cn', domain: str = 'it') -> str:
        # 创建一个 Translator 对象，并配置代理
        proxies = {
            'http': '127.0.0.1:1080'
        }
        translator = googletrans.Translator(
            proxies=proxies  # 这个代理并没有用, 想走代理需要开启tun模式或者使用proxychains等代理软件
        )
        translated_text = translator.translate(text, dest=to_lang)
        return translated_text.text
